//
//  TakeVideoViewController.m
//  NvSellerShow
//
//  Created by dx on 17/6/27.
//  Copyright © 2017年 Meicam. All rights reserved.
//

#import "TakeVideoViewController.h"
#import "NvGridView.h"
#import "NvsVideoTrack.h"
#import "NvsVideoClip.h"
#import "PlayerControllView.h"
#import <Photos/Photos.h>

@interface TakeVideoViewController ()<NvsStreamingContextDelegate> {
    NvsStreamingContext *_context;
    unsigned int _currentDeviceIndex;
    BOOL _isNeedRestartPreview;
    BOOL _isRecording;
    BOOL _isflashOn;
    BOOL _enableRotation;//是否允许旋转（注意在视频录制过程中禁止屏幕旋转）
    BOOL _isRotate;
    NvsRational _aspectRatio;
    PHAsset *_videoAsset;
    NSTimer *timer,*sliderTimer;
    NSInteger time;
    NvsTimeline *timeline;
    UIImageView *imageView;
    BOOL isPlaying;
    int64_t currenttime;//当前播放的时间
    float pan,scan;
    //TakeVideoPreViewController *preViewController;
}

@property (nonatomic, strong) NvGridView *gridView;
@property (nonatomic, strong) PlayerControllView *playerControllView;
@property (weak, nonatomic) IBOutlet UIView *nagationBar;
@property (weak, nonatomic) IBOutlet UIImageView *backImage;
@property (weak, nonatomic) IBOutlet NvsLiveWindow *liveWindow;
@property (weak, nonatomic) IBOutlet UIButton *cancelBtn;
@property (weak, nonatomic) IBOutlet UIButton *sureBtn;
@property (weak, nonatomic) IBOutlet UIButton *recordBtn;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UIButton *flashBtn;
@property (weak, nonatomic) IBOutlet UIButton *gridBtn;
@property (weak, nonatomic) IBOutlet UIButton *changeCamera;

- (IBAction)cancleBtn:(UIButton *)sender;
- (IBAction)sureBtn:(UIButton *)sender;
- (IBAction)recordBtn:(UIButton *)sender;
- (IBAction)startFlash:(UIButton *)sender;
- (IBAction)showGrid:(UIButton *)sender;
- (IBAction)changeCamera:(UIButton *)sender;

@property (strong, nonatomic) NSString *urlVideo;

@end

@implementation TakeVideoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //设置返回事件
    [self.backImage addTapGestureRecognizer:@selector(back) target:self];
    //初始化相机
    [self cameraDistrict];
    
    //添加栅格
    self.gridView.frame = self.liveWindow.bounds;
    [self.liveWindow addSubview:self.gridView];
    
    pan = 0;
    scan = 1;
    
    if ([self.from isEqualToString:@"相册"]) {
        self.gridBtn.hidden = YES;
        self.changeCamera.hidden = YES;
        self.flashBtn.hidden = YES;
    }
    
}

- (void)createTimer {
    sliderTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(handleSlider) userInfo:nil repeats:YES];
}

- (void)back {
    _context.delegate = nil;
    [_context stop];
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)cameraDistrict {
    _isRecording = false;
    _currentDeviceIndex = 0;
    
    _context = [NvsStreamingContext sharedInstanceWithFlags:NvsStreamingContextFlag_Support4KEdit];
    
    _context.delegate = self;
    
    if (!_context)
        return;
    
    if ([_context captureDeviceCount] == 0) {
        //[self showAlert:@"没有可用于采集的设备"];
        return;
    }
    
    if (![_context connectCapturePreviewWithLiveWindow:self.liveWindow]) {
        //[self showAlert:@"连接预览窗口失败"];
        return;
    }
    
    if (![_context startCapturePreview:0 videoResGrade:NvsVideoCaptureResolutionGradeHigh flags:0 aspectRatio:nil]) {
        //[self showAlert:@"启动预览失败"];
        return;
    }
    
    [self.liveWindow addTapGestureRecognizer:@selector(startAutoFocus:) target:self];
    
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    self.urlVideo = [NSString stringWithFormat:@"%@/%@record.mov",path,[Utils getTimeAndRandom]];
    
    imageView = [[UIImageView alloc] init];
    imageView.image = [self imageFromBundle:@"player_preview"];
    imageView.userInteractionEnabled = YES;
    [self.liveWindow addSubview:imageView];
    [imageView addTapGestureRecognizer:@selector(playOrPause) target:self];
    imageView.hidden = YES;
    
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.liveWindow.mas_centerX);
        make.centerY.equalTo(self.liveWindow.mas_centerY);
        make.width.height.equalTo(@72);
    }];
    
    self.playerControllView.frame = CGRectMake(0, self.view.frame.size.width+24, self.view.frame.size.width, 40);
    [self.view addSubview:self.playerControllView];
    
    [self.playerControllView.slider addTarget:self action:@selector(sliderChange) forControlEvents:UIControlEventValueChanged];
    currenttime = 0;
    
    
    //如果是选择视频片段
    if (self.avasset) {
        [self showPreviewVideo];
        imageView.hidden = NO;
        self.sureBtn.hidden = NO;
        self.cancelBtn.hidden = NO;
        self.recordBtn.hidden = YES;
        self.playerControllView.hidden = NO;
    }
}

- (void)playOrPause {
    if (isPlaying) {
        [sliderTimer invalidate];
        sliderTimer = nil;
        isPlaying = NO;
        imageView.image = [self imageFromBundle:@"player_preview"];
        [_context stop];
    } else {
        [self createTimer];
        [sliderTimer fire];
        isPlaying = YES;
        currenttime = self.playerControllView.slider.value*timeline.duration;
        [_context playbackTimeline:timeline startTime:currenttime endTime:timeline.duration videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize preload:YES flags:0];
        imageView.image = [self imageFromBundle:@"player_stop"];
        self.timeLabel.text = [NSString stringWithFormat:@"%@/%@",self.playerControllView.currentLabel.text,self.playerControllView.totalLabel.text];
    }
}

- (void)startAutoFocus:(UITapGestureRecognizer *)tapGestureRecognizer {
    CGPoint point = [tapGestureRecognizer locationInView:self.liveWindow];
    [_context startAutoFocus:point];
}

#pragma mark - delegate

- (void)didPlaybackStopped:(NvsTimeline *)timeline {
    NSLog(@"stop--\n");
}

- (void)didPlaybackEOF:(NvsTimeline *)timeline1 {
    imageView.image = [self imageFromBundle:@"player_preview"];
    [_context seekTimeline:timeline1 timestamp:0 videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize flags:0];
}

#pragma mark - handleSlider

- (void)handleSlider {
    int64_t currentPosition = [_context getTimelineCurrentPosition:timeline];
    int64_t totalTime = timeline.duration;
    self.playerControllView.currentLabel.text = [Utils stringWithTime:1.0*currentPosition/NS_TIME_BASE];
    self.playerControllView.totalLabel.text = [Utils stringWithTime:1.0*totalTime/NS_TIME_BASE ];
    [self.playerControllView.slider setValue:1.0*currentPosition/totalTime animated:YES];
    self.timeLabel.text = [NSString stringWithFormat:@"%@/%@",self.playerControllView.currentLabel.text,self.playerControllView.totalLabel.text];
}

- (void)sliderChange {
    [_context stop];
    int64_t currentPosition = [_context getTimelineCurrentPosition:timeline];
    int64_t totalTime = timeline.duration;
    self.playerControllView.currentLabel.text = [Utils stringWithTime:1.0*currentPosition/NS_TIME_BASE];
    self.playerControllView.totalLabel.text = [Utils stringWithTime:1.0*totalTime/NS_TIME_BASE ];
    imageView.image = [self imageFromBundle:@"player_preview"];
    currenttime = self.playerControllView.slider.value*timeline.duration;
    [_context seekTimeline:timeline timestamp:currenttime videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize flags:0];
    self.timeLabel.text = [NSString stringWithFormat:@"%@/%@",self.playerControllView.currentLabel.text,self.playerControllView.totalLabel.text];
}

#pragma mark - Getter
- (NvGridView *)gridView {
    if (!_gridView) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
        NSBundle *myBundle = [NSBundle bundleWithPath:path];
        _gridView = [[myBundle loadNibNamed:@"NvGridView" owner:self options:nil] lastObject];
    }
    return _gridView;
}

- (PlayerControllView *)playerControllView {
    if (!_playerControllView) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
        NSBundle *myBundle = [NSBundle bundleWithPath:path];
        _playerControllView = [[myBundle loadNibNamed:@"PlayerControllView" owner:self options:nil] lastObject];
    }
    return _playerControllView;
}

#pragma mark - Click
- (IBAction)cancleBtn:(UIButton *)sender {
    //如果从相册选择视频进来点击取消直接返回上一页
    if ([self.from isEqualToString:@"相册"]) {
        [_context stop];
        [self dismissViewControllerAnimated:YES completion:NULL];
        return;
    }
    self.nagationBar.hidden = NO;
    self.sureBtn.hidden = YES;
    self.cancelBtn.hidden = YES;
    self.recordBtn.hidden = NO;
    imageView.hidden = YES;
    self.playerControllView.hidden = YES;
    [self.flashBtn setSelected:NO];
    [self.gridBtn setSelected:NO];
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    BOOL bRet = [fileMgr fileExistsAtPath:self.urlVideo];
    if (bRet) {
        NSError *err;
        [fileMgr removeItemAtPath:self.urlVideo error:&err];
    }
    
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSArray *array = [fileMgr contentsOfDirectoryAtPath:path error:nil];
    for (NSString *name in array) {
        if ([fileMgr fileExistsAtPath:[NSString stringWithFormat:@"%@/%@",path,name]]) {
            [fileMgr removeItemAtPath:[NSString stringWithFormat:@"%@/%@",path,name] error:nil];
        }
    }
    self.urlVideo = [NSString stringWithFormat:@"%@/%@record.mov",path,[Utils getTimeAndRandom]];
    
    imageView.image = [self imageFromBundle:@"player_preview"];
    [sliderTimer invalidate];
    sliderTimer = nil;
    self.timeLabel.text = @"00:00";
    [_context connectCapturePreviewWithLiveWindow:self.liveWindow];
    [_context startCapturePreview:0 videoResGrade:NvsVideoCaptureResolutionGradeHigh flags:0 aspectRatio:nil];
}

- (IBAction)sureBtn:(UIButton *)sender {
    self.nagationBar.hidden = NO;
    //销毁delegate不然会循环引用
    [_context stop];
    _context.delegate = nil;
    self.sureBtn.hidden = NO;
    self.cancelBtn.hidden = NO;
    if(self.avasset!=nil) {//外界传入AVasset
        if ([self.delegate respondsToSelector:@selector(takeVideoViewController:didSelectVideo:pan: scan:)]) {
            //播放的时候scan不能设置为1，设为1后画面会显示不完整，但实际视频传过去的是1（1代表整个显示的宽度）
            [self.delegate takeVideoViewController:self didSelectVideo:self.avasset pan:pan scan:1];
        }
    } else {//自己录制
        [self saveVideoToDocument];
    }
}

- (IBAction)recordBtn:(UIButton *)sender {
    self.nagationBar.hidden = YES;
    if (!sender.selected) {
        
        [_context startRecording:self.urlVideo];
        [self startTimer];
    } else {
        [_context stopRecording];
        [self cancleTimer];
        [self showPreviewVideo];
        self.sureBtn.hidden = NO;
        self.cancelBtn.hidden = NO;
        self.recordBtn.hidden = YES;
        self.playerControllView.hidden = NO;
    }
    sender.selected = !sender.selected;
}

- (IBAction)startFlash:(UIButton *)sender {
    [_context toggleFlash:!sender.selected];
    sender.selected = !sender.selected;
}

- (IBAction)showGrid:(UIButton *)sender {
    self.gridView.hidden = sender.selected;
    sender.selected = !sender.selected;
}

- (IBAction)changeCamera:(UIButton *)sender {
    [_context stopRecording];
    [self cancleTimer];
    self.timeLabel.text = @"00:00";
    self.recordBtn.selected = NO;
    if (sender.selected) {
        [_context startCapturePreview:0 videoResGrade:NvsVideoCaptureResolutionGradeHigh flags:0 aspectRatio:nil];
        self.flashBtn.enabled = YES;
    } else {
        [_context startCapturePreview:1 videoResGrade:NvsVideoCaptureResolutionGradeHigh flags:0 aspectRatio:nil];
        self.flashBtn.selected = NO;
        self.flashBtn.enabled = NO;
    }
    sender.selected = !sender.selected;
}

//MARK:保存视频
- (void)saveVideoToDocument {
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(globalQueue, ^(void) {
        NSMutableArray *videoIds = [NSMutableArray array];
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if (status == PHAuthorizationStatusAuthorized) {
                [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                    
                    PHAssetChangeRequest *req = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:[NSURL fileURLWithPath:self.urlVideo]];
                    [videoIds addObject:req.placeholderForCreatedAsset.localIdentifier];
                    
                    
                } completionHandler:^(BOOL success, NSError * _Nullable error) {
                    
                    NSLog(@"success = %d, error = %@", success, error);
                    
                    if (success) {
                        PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:videoIds options:nil];
                        [result enumerateObjectsUsingBlock:^(PHAsset * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                            
                            _videoAsset = obj;
                            *stop = YES;
                        }];
                    }
                    dispatch_semaphore_signal(sema);
                }];
            } else {
                //没有授权
                dispatch_semaphore_signal(sema);
            }
        }];
        
        
    });
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    NSLog(@"保存完了");
    TakeVideoViewController __weak *weakSelf = self;
    [[PHCachingImageManager new] requestAVAssetForVideo:_videoAsset options:[PHVideoRequestOptions new] resultHandler:^(AVAsset * avasset, AVAudioMix * audioMix, NSDictionary * info) {
          dispatch_async(dispatch_get_main_queue(), ^{
              ///保存完视频获取asset
              NSLog(@"%@",avasset);
              NSFileManager *fileMgr = [NSFileManager defaultManager];
              BOOL bRet = [fileMgr fileExistsAtPath:self.urlVideo];
              if (bRet) {
                  NSError *err;
                  [fileMgr removeItemAtPath:self.urlVideo error:&err];
              }
              if (avasset!=nil && [weakSelf.delegate respondsToSelector:@selector(takeVideoViewController:didSelectVideo:pan:scan:)]) {
                  [weakSelf.delegate takeVideoViewController:self didSelectVideo:avasset pan:pan scan:scan];
              }
          });
    }];
}

- (void)showPreviewVideo {
    imageView.hidden = NO;
    [self createTimeline];
    [_context seekTimeline:timeline timestamp:1 videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize flags:0];
    self.playerControllView.totalLabel.text = [self getStringTime:timeline.duration*1.0/NS_TIME_BASE];
}

- (void)createTimeline {
    NvsVideoResolution videoEditRes;
    if(self.editmode == NvSSVideoCreateScaleSquare) {
        videoEditRes.imageWidth = 720;
        videoEditRes.imageHeight = 720;
    } else if(self.editmode == NvSSVideoCreateScaleHorizontal){
        videoEditRes.imageWidth = 1280;
        videoEditRes.imageHeight = 720;
    } else {
        videoEditRes.imageWidth = 720;
        videoEditRes.imageHeight = 1280;
    }
    videoEditRes.imagePAR = (NvsRational){1, 1};
    NvsRational videoFps = {25, 1};
    NvsAudioResolution audioEditRes;
    audioEditRes.sampleRate = 48000;
    audioEditRes.channelCount = 2;
    audioEditRes.sampleFormat = NvsAudSmpFmt_S16;
    timeline = [_context createTimeline:&videoEditRes videoFps:&videoFps audioEditRes:&audioEditRes];
    [_context connectTimeline:timeline withLiveWindow:self.liveWindow];
    NvsVideoTrack *videoTrack = [timeline appendVideoTrack];
    [videoTrack removeAllClips];
    if (self.avasset!=nil) {
        self.urlVideo = ((AVURLAsset*)self.avasset).URL.absoluteString;
    }
    NvsVideoClip *videoClip = [videoTrack appendClip:self.urlVideo];
    pan = 0;
    //播放的时候scan不能设置为1，设为1后画面会显示不完整，但实际视频传过去的是1
//    scan = self.view.frame.size.width/1080.0;
    scan = 1;
    [videoClip setPan:pan andScan:scan];
    
}

- (void)startTimer {
    time = 0;
    timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerCallback) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}

- (void)timerCallback {
    time++;
    dispatch_async(dispatch_get_main_queue(), ^{
        self.timeLabel.text = [self getStringTime:time];
    });
}

- (void)cancleTimer {
    time = 0;
    [timer invalidate];
}

- (NSString *)getStringTime:(NSInteger)second {
    NSInteger hh = second / 3600;
    NSInteger mm = second %3600 / 60;
    NSInteger ss = second % 60;
    NSString *str = @"";
    if (hh>0) {
        str = [NSString stringWithFormat:@"%02ld:%02ld:%02ld",(long)hh,(long)mm,(long)ss];
    } else {
        str = [NSString stringWithFormat:@"%02ld:%02ld",(long)mm,(long)ss];
    }
    return str;
}

- (void)dealloc {
    [_context stop];
    [_context stopRecording];
    [self cancleTimer];
    NSLog(@"销毁\n");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    NSLog(@"内存警告\n");
}

- (UIImage *)imageFromBundle:(NSString*)imageName {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
    NSBundle *myBundle = [NSBundle bundleWithPath:path];
    NSString *imagePath = [myBundle pathForResource:imageName ofType:@"png"];
    UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
    return image;
}

@end
